﻿/*
Commerce by Onex – eCommerce software platform (www.ecommerce.byonex.com)
Copyright (C) 2008-2010 by Onex Group

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using ShopModel;

namespace ShopDAO
{
    public class ShipmentDAO
    {
        private string connectionString;

        private SqlConnection Connection()
        {
            return new SqlConnection(connectionString);
        }

        public ShipmentDAO()
        {
            connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["csShop"].ConnectionString;
        }

        /// <summary>
        /// Zapisuje możliwość przesyłki w bazie Danych (Save shipment option in the database)
        /// </summary>
        /// <param name="PaymentID">Id płatności (Payment id)</param>
        /// <param name="ShipmentID">Id Wysyłki (Shipment id)</param>
        /// <returns>Jeśli operacja zakończona powodzeniem zwraca 'True' (Returns ‘true’ is operation succeeded)</returns>
        public bool SaveShipmentPossibility(int PaymentID, int ShipmentID)
        {
            SqlConnection sqlC = Connection();
            SqlCommand command = sqlC.CreateCommand();

            command.CommandText = "SaveShipmentPossibility";
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@PaymentID", PaymentID));
            command.Parameters.Add(new SqlParameter("@ShipmentID", ShipmentID));

            try
            {
                sqlC.Open();

                command.ExecuteNonQuery();

                return true;
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);

                return false;
            }
            finally
            {
                sqlC.Close();
            }
        }

        /// <summary>
        /// Usuwa możliwość przesyłki w bazie Danych (Deletes shipment option from the database)
        /// </summary>
        /// <param name="PaymentID">Id płatności (Payment id)</param>
        /// <param name="ShipmentID">Id Wysyłki (Shipment id)</param>
        /// <returns>Jeśli operacja zakończona powodzeniem zwraca 'True' (Returns ‘true’ is operation succeeded)</returns>
        public bool DeleteShipmentPossibility(int PaymentID, int ShipmentID)
        {
            SqlConnection sqlC = Connection();
            SqlCommand command = sqlC.CreateCommand();

            command.CommandText = "DeleteShipmentPossibility";
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@PaymentID", PaymentID));
            command.Parameters.Add(new SqlParameter("@ShipmentID", ShipmentID));

            try
            {
                sqlC.Open();

                command.ExecuteNonQuery();

                return true;
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);
                return false;
            }
            finally
            {
                sqlC.Close();
            }
        }

        /// <summary>
        /// Pobiera możliwości wysyłki zapisane w bazie danych (Downloads shipment options saved in the database)
        /// </summary>
        /// <param name="PaymentID">Id płatności (Payment id)</param>
        /// <param name="Active">Czy opcja jest aktywna (Whether the option is active)</param>
        /// <param name="languageID">Id języka w jakim wyświetlana jest strona (Language ID in which page is displayed)</param>
        /// <returns>Lista obiektów typu ShipmentType przechowująca dostępne możliwości wysyłki (List of ShipmentType objects storing available shipment options)</returns>
        public List<ShipmentType> GetShipmentPossibilities(int PaymentID, int? languageID)
        {
            List<ShipmentType> result = new List<ShipmentType>();

            SqlConnection sqlC = Connection();
            SqlCommand command = sqlC.CreateCommand();
            SqlDataReader sqlR;

            command.CommandText = "GetShipmentPossibilities";
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@PaymentID", PaymentID));
            command.Parameters.Add(new SqlParameter("@LanguageID", languageID));

            try
            {
                sqlC.Open();

                sqlR = command.ExecuteReader();

                while (sqlR.Read())
                {
                    result.Add(new ShipmentType((int)sqlR["IDshipment"], (string)sqlR["ShipmentName"], GetShipmentPriceValue(sqlR["CountryShipmentPrice"]), GetShipmentPriceValue(sqlR["EUShipmentPrice"]), GetShipmentPriceValue(sqlR["WorldShipmentPrice"])));
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);
            }
            finally
            {
                sqlC.Close();
            }

            return result;
        }

        /// <summary>
        /// Zapisuje w bazie nową możliwośc wysyłki (Saves new shipment option in the database)
        /// </summary>
        /// <param name="ShipmentID">Unikalne id wysyłki (Unique shipment id)</param>
        /// <param name="Name"></param>
        /// <param name="CountryShipmentPrice">Cena przesyłki krajowej (Inladn shipment price)</param>
        /// <param name="EUShipmentPrice">Cena przesyłki do Unii Europejskiej (EU countries shipment price)</param>
        /// <param name="WorldShipmentPrice">Cena przesyłki do krajów z poza EU (Shipment prcie for countries outside of EU)</param>
        /// <param name="languageID">Unikalne id języka w jakim jest wyświetlana strona (Unique language ID in which page is displayed)</param>
        /// <returns>Jeśli operacja zakończona powodzeniem zwraca 'True' (Returns ‘true’ is operation succeeded)</returns>
        public bool SaveShipmentType(int? ShipmentID, string Name, decimal CountryShipmentPrice, decimal EUShipmentPrice, decimal WorldShipmentPrice, int? languageID)
        {
            SqlConnection sqlC = Connection();
            SqlCommand command = sqlC.CreateCommand();

            command.CommandText = "SaveShipmentType";
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@Name", Name));

            if (CountryShipmentPrice < 0)
            {
                command.Parameters.Add(new SqlParameter("@CountryShipmentPrice", DBNull.Value));
            }
            else
            {
                command.Parameters.Add(new SqlParameter("@CountryShipmentPrice", CountryShipmentPrice));
            }

            if (EUShipmentPrice < 0)
            {
                command.Parameters.Add(new SqlParameter("@EUShipmentPrice", DBNull.Value));
            }
            else
            {
                command.Parameters.Add(new SqlParameter("@EUShipmentPrice", EUShipmentPrice));
            }

            if (WorldShipmentPrice < 0)
            {
                command.Parameters.Add(new SqlParameter("@WorldShipmentPrice", DBNull.Value));
            }
            else
            {
                command.Parameters.Add(new SqlParameter("@WorldShipmentPrice", WorldShipmentPrice));
            }

            command.Parameters.Add(new SqlParameter("@LanguageID", languageID));

            if (ShipmentID != null)
                command.Parameters.Add(new SqlParameter("@ShipmentID", ShipmentID));

            try
            {
                sqlC.Open();

                command.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);
                return false;
            }
            finally
            {
                sqlC.Close();
            }
        }

        /// <summary>
        /// Usuwa możliwość wysyłki z bazy danych (Deletes shipment option from the database)
        /// </summary>
        /// <param name="ShipmentID">Unikalne id wysyłki (Unique shipment id)</param>
        /// <returns>Jeśli operacja zakończona powodzeniem zwraca 'True' (Returns ‘true’ is operation succeeded)</returns>
        public bool DeleteShipmentType(int ShipmentID)
        {
            SqlConnection sqlC = Connection();
            SqlCommand command = sqlC.CreateCommand();

            command.CommandText = "DeleteShipmentType";
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@ShipmentID", ShipmentID));

            try
            {
                sqlC.Open();

                command.ExecuteNonQuery();

                return true;
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);
                return false;
            }
            finally
            {
                sqlC.Close();
            }
        }

        /// <summary>
        /// Pobiera opcję wysyłki po unukalnym id jednaj z opcji wysyłki (Downloads shipment option by unique ID of one of the shipment option)
        /// </summary>
        /// <param name="ShipmentID">Unikalne id wysyłki (Unique shipment id)</param>
        /// <param name="languageID">Unikalne id języka w jakim jest wyświetlana strona (Unique language ID in which page is displayed)</param>
        /// <returns>Obiekt typu ShipmentType zawierający informacje  wysyłce (ShipmentType object cintaining information about shipment)</returns>
        public ShipmentType GetShipmentType(int ShipmentID, int? languageID)
        {

            ShipmentType result = null ;

            SqlConnection sqlC = Connection();
            SqlCommand command = sqlC.CreateCommand();
            SqlDataReader sqlR;

            command.CommandText = "GetShipmentTypes";
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@ShipmentID", ShipmentID));
            command.Parameters.Add(new SqlParameter("@LanguageID", languageID));

            try
            {
                sqlC.Open();

                sqlR = command.ExecuteReader();

                if (sqlR.Read())
                {
                    result = new ShipmentType((int)sqlR["IDshipment"], (string)sqlR["ShipmentName"], GetShipmentPriceValue(sqlR["CountryShipmentPrice"]), GetShipmentPriceValue(sqlR["EUShipmentPrice"]), GetShipmentPriceValue(sqlR["WorldShipmentPrice"]));
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);
            }
            finally
            {
                sqlC.Close();
            }

            return result;
        }


        /// <summary>
        /// Pobiera wszystkie z opcji wysyłki (Downloads all from shipment option)
        /// </summary>
        /// <param name="languageID">Unikalne id języka w jakim jest wyświetlana strona (Unique language ID in which page is displayed)</param>
        /// <returns>Lista opiektów typu ShipmentType, opisijących opcje wysyłki (List of ShipmentTye objects discribing shipment option)</returns>
        public List<ShipmentType> GetShipmentTypes(int? languageID)
        {
            List<ShipmentType> result = new List<ShipmentType>();

            SqlConnection sqlC = Connection();
            SqlCommand command = sqlC.CreateCommand();
            SqlDataReader sqlR;

            command.CommandText = "GetShipmentTypes";
            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.Add(new SqlParameter("@LanguageID", languageID));

            try
            {
                sqlC.Open();

                sqlR = command.ExecuteReader();

                while (sqlR.Read())
                {
                    result.Add(new ShipmentType((int)sqlR["IDshipment"], (string)sqlR["ShipmentName"], GetShipmentPriceValue(sqlR["CountryShipmentPrice"]), GetShipmentPriceValue(sqlR["EUShipmentPrice"]), GetShipmentPriceValue(sqlR["WorldShipmentPrice"])));
                }

                sqlR.Close();
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);
            }
            finally
            {
                sqlC.Close();
            }

            return result;
        }

        /// <summary>
        /// Sprawdza czy można skorzystać w wybranej opcji wysyłki dla danego kraju (Checks whether it is posiible to use chosen shipment option for every country)
        /// </summary>
        /// <param name="paymentID">Unikalne id płatności (Unique payment id)</param>
        /// <param name="shipmentID">Unikalne id wysyłki (Unique shipmen id)</param>
        /// <param name="countryID">Unikalne id kraju (Unique country id)</param>
        /// <returns>Zwraca 'true' jeśli wysyłka jest możliwa (Returns ‘true’ id shipment is possible)</returns>
        public bool CheckShipmentPossiblities(int paymentID, int shipmentID, int countryID)
        {
            SqlConnection connection = Connection();
            SqlCommand command = connection.CreateCommand();
            command.CommandText = "CheckShipmentPosibilities";
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@shipment_id", shipmentID));
            command.Parameters.Add(new SqlParameter("@country_id", countryID));
            command.Parameters.Add(new SqlParameter("@payment_id", paymentID));

            try
            {
                connection.Open();
                return (bool)command.ExecuteScalar();
            }
            catch (Exception ex)
            {
                ErrorLogger.LogError(ex);
                return false;
            }
            finally
            {
                connection.Close();
            }
        }

        private decimal GetShipmentPriceValue(object value)
        {
            if (value == DBNull.Value)
            {
                return -1;
            }
            else
            {
                return (decimal)value;
            }
        }

    }
}
